import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_ui/common_ui.dart';
import 'package:common_ui/components/common_avatar.dart';
import 'package:common_ui/components/common_button.dart';
import 'package:common_ui/components/common_edit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';
import 'package:manager/base/base_controller.dart';
import 'package:manager/configs/image_path.dart';
import 'package:manager/configs/theme_data.dart';
import 'package:manager/exts/app_ext.dart';
import 'package:manager/res/color.dart';

import '../exts/route_ext.dart';
import '../exts/string_ext.dart';

///圆角网络图片组件
Widget radiusImage(String url,
    {double? radius,
    dynamic key,
    BoxFit? fit,
    double? wide,
    double? height,
    double? loadingHeight}) {
  return ClipRRect(
    borderRadius: BorderRadius.circular(radius ?? 0),
    child: CachedNetworkImage(
      key: ValueKey(key),
      imageUrl: url,
      width: wide ?? double.infinity,
      height: height,
      fit: fit ?? BoxFit.cover,
      placeholder: (c, w) {
        return Container(
          width: wide ?? double.infinity,
          height: loadingHeight,
          decoration: BoxDecoration(
              color: ColorPool.activity_bg,
              borderRadius: BorderRadius.circular(6)),
        );
      },
      errorWidget: (c, u, o) {
        return Image.asset('${ImagePath.IMAGE_PATH}app_icon.jpg');
      },
    ),
  );
}

///顶部搜索框
Widget topSearchBar() {
  return Container(
    padding: const EdgeInsets.only(left: 12),
    width: double.infinity,
    height: 35,
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: ColorPool.activity_bg, borderRadius: BorderRadius.circular(20)),
    child: TextField(
      enabled: false,
      style: const TextStyle(color: Colors.black87, fontSize: 14),
      decoration: InputDecoration(
          contentPadding: const EdgeInsets.only(left: -8),
          isCollapsed: true,
          icon: Icon(
            CupertinoIcons.search,
            size: 24,
            color: Colors.grey[400],
          ),
          hintText: '输入店铺名称或商品名称',
          hintStyle: const TextStyle(fontSize: 14, color: Colors.grey),
          border: InputBorder.none),
    ),
  ).onClick(() => toSearch());
}

Widget networkImage(String? url, {double? height, double? wide, BoxFit? fit}) {
  return Image.network(
    url ?? '',
    errorBuilder: (c, o, s) {
      return Container(
        width: double.infinity,
        height: height,
        decoration: const BoxDecoration(color: ColorPool.activity_bg),
        child: const Icon(
          Icons.broken_image_outlined,
          size: 36,
          color: Colors.grey,
        ),
      );
    },
    width: wide,
    height: height,
    fit: fit ?? BoxFit.cover,
  );
}

extension WidgetAlignment on Widget {
  ///设置alignment 值
  Widget setAlign(AlignmentGeometry align) {
    return UnconstrainedBox(
      alignment: align,
      child: this,
    );
  }

  Widget setBackColor(Color color) {
    return Container(
      color: color,
      child: this,
    );
  }

  ///设置组件点击事件
  Widget onClick(VoidCallback onClick, {Key? key}) {
    return GestureDetector(
      key: key,
      onTap: () => onClick.call(),
      child: this,
    );
  }
}

///设置margin 值
extension WidgetMargin on Widget {
  Widget setMargin(EdgeInsetsGeometry margin) {
    return Container(
      margin: margin,
      child: this,
    );
  }
}

///设置padding值
extension WidgetPadding on Widget {
  Widget setPadding(EdgeInsetsGeometry padding) {
    return Container(
      color: Colors.white,
      padding: padding,
      child: this,
    );
  }
}

///单个text
Widget singleText(String text,
    {TextStyle? style,
    double? height,
    double? width,
    Color? bgColor,
    Alignment? alignment,
    EdgeInsetsGeometry? margin,
    EdgeInsetsGeometry? padding,
    BorderRadiusGeometry? borderRadius,
    int? maxLine,
    TextOverflow? overFlow}) {
  return Container(
    alignment: alignment,
    margin: margin,
    padding: padding,
    decoration: BoxDecoration(
        color: bgColor ?? Colors.white, borderRadius: borderRadius),
    height: height,
    width: width,
    child: Text(
      text,
      maxLines: maxLine,
      overflow: overFlow,
      style: style,
    ),
  );
}

///竖直线
Widget verticalLine(
    {Color? color, double? height, double? wide, EdgeInsetsGeometry? margin}) {
  return Container(
    height: height ?? 24,
    margin: margin,
    width: wide ?? 4,
    decoration: BoxDecoration(
        color: color ?? ColorPool.theme_color,
        borderRadius: BorderRadius.circular(wide ?? 4 / 2)),
  );
}

///竖直线
Widget horizonLine(
    {Color? color, double? height, double? wide, EdgeInsetsGeometry? margin}) {
  return Container(
    height: height ?? 1,
    margin: margin,
    width: wide,
    decoration: BoxDecoration(border: line(lineColor: color, height: height)),
  );
}

///搜索框
Widget searchBar(String hint, Function(String)? search,
    {Color? barBgColor, bool? autoFocus, Function(String)? onChange}) {
  return Container(
    padding: const EdgeInsets.only(left: 12),
    width: double.infinity,
    height: 40,
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: barBgColor ?? Colors.white,
        borderRadius: BorderRadius.circular(20)),
    child: TextField(
      style: Styles.textCommon,
      enabled: search != null,
      autofocus: autoFocus ?? false,
      textInputAction: TextInputAction.search,
      onChanged: (value) => onChange?.call(value),
      onSubmitted: (value) {
        search?.call(value);
      },
      decoration: InputDecoration(
          contentPadding: const EdgeInsets.only(left: -8),
          isCollapsed: true,
          icon: Icon(
            CupertinoIcons.search,
            size: 24,
            color: Colors.grey[400],
          ),
          hintText: hint,
          border: InputBorder.none),
    ),
  );
}

///底部分割线
Border line({Color? lineColor, double? height}) {
  return Border(
      bottom: BorderSide(
          color: lineColor ?? ColorPool.line_color, width: height ?? 1));
}

///铺满宽度的圆角按钮
Widget getCommonButton(String text,
    {required VoidCallback onPress,
    EdgeInsetsGeometry? margin,
    Color? bgColor,
    Color? textColor,
    double? radius}) {
  return CommonButton(
    text,
    onPress: onPress,
    margin: margin ?? const EdgeInsets.all(16),
    wide: double.infinity,
    bgColor: bgColor,
    textStyle: TextStyle(color: textColor, fontSize: 16),
    height: 45,
    round: radius,
    shape: (radius ?? 0) < 45 / 2 ? ShapeData.round : ShapeData.circle,
    tapInterval: 500,
  );
}

///铺满宽度的圆角按钮,背景色为渐变色
Widget getGradientButton(String text,
    {required VoidCallback onPress,
    EdgeInsetsGeometry? margin,
    Color? bgColor,
    double? height,
    TextStyle? style,
    double? radius}) {
  return CommonButton(
    text,
    onPress: onPress,
    textStyle: style,
    margin: margin ?? const EdgeInsets.all(16),
    wide: double.infinity,
    bgColor: bgColor ?? Colors.transparent,
    height: height ?? 45,
    shape: (radius ?? 0) < 45 / 2 ? ShapeData.round : ShapeData.circle,
    gradient: bgColor == null
        ? const LinearGradient(colors: [
            Color.fromARGB(255, 72, 147, 245),
            Color.fromARGB(255, 36, 209, 230)
          ])
        : null,
    round: radius,
    tapInterval: 500,
  );
}

///单个编辑框
Widget getSingleEdit(
    {String? content,
    Key? key,
    String? hint,
    int? maxLines,
    int? minLines,
    Color? lineColor,
    Color? color,
    double? lineHeight,
    EdgeInsetsGeometry? contentPadding,
    Function(String)? onChange,
    EdgeInsetsGeometry? margin,
    TextStyle? textStyle,
    TextInputType? inputType,
    bool? enable}) {
  return SingleEdit(
    key: key,
    color: color ?? Colors.white,
    minLines: minLines,
    maxLines: maxLines,
    onChanged: onChange,
    style: textStyle,
    enable: enable,
    textInputAction: TextInputAction.done,
    keyboardType: inputType,
    controller: content == null ? null : TextEditingController(text: content),
    decoration: InputDecoration(
      hintText: hint,
      isDense: true,
      border: lineColor == null
          ? InputBorder.none
          : OutlineInputBorder(
              borderSide: BorderSide(
                  color: ColorPool.line_color, width: lineHeight ?? 1)),
      contentPadding: contentPadding ?? const EdgeInsets.all(16),
    ),
  );
}

///圆形头像组件
Widget getAvatar(String? url, double size, {EdgeInsetsGeometry? margin}) {
  ImageProvider? image;
  if (url.isNullEmpty()) {
    image = const AssetImage('${ImagePath.IMAGE_PATH}header.png');
  } else {
    image = NetworkImage(url!);
  }
  return Avatar(
    backgroundImage: image,
    size: size,
    margin: margin,
  );
}

///向右的箭头组件
Widget getArrowRightIcon({double? size}) {
  return Icon(
    Icons.arrow_forward_ios_outlined,
    color: Colors.grey[400],
    size: size ?? 20,
  );
}

///左边标题,右边内容不带箭头的组件,带有下划线
Widget getCommonTitleContent(
    {String? title, String? content, Color? lineColor, double? lineHeight}) {
  return TitleContentText(
    title: title,
    content: content,
    padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
    titleStyle: Styles.textCommon,
    contentStyle: Styles.textCommon,
    border: Border(
        bottom: BorderSide(
            color: lineColor ?? ColorPool.line_color, width: lineHeight ?? 1)),
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    alignment: Alignment.centerRight,
  );
}

///左边标题,右边内容带箭头的组件,带有下划线
Widget getArrowTitleContent(
    {String? title, String? content, int? maxLines, Function()? onClick}) {
  return TitleContentIcon(
    title: title,
    content: content,
    padding: const EdgeInsets.fromLTRB(16, 12, 6, 12),
    titleStyle: Styles.textCommon,
    contentStyle: Styles.textCommon,
    onClick: onClick,
    backColor: Colors.white,
    maxLines: maxLines,
    border: const Border(bottom: BorderSide(color: ColorPool.line_color)),
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    alignment: Alignment.centerRight,
    contentIcon: getArrowRightIcon(),
  );
}

///提示信息组件
Widget notifyView(String notify) {
  return SingleText(
    notify,
    height: 35,
    alignment: Alignment.centerLeft,
    textStyle: Styles.textMedium,
    margin: const EdgeInsets.only(left: 16),
    bgColor: ColorPool.activity_bg_dark,
  );
}

///toolbar 右侧的操作按钮
Widget actionButton(String text, VoidCallback onPress) {
  return TextButton(
      onPressed: onPress,
      child: Text(
        text,
        style: Styles.textMediumWhite,
      ));
}

@optionalTypeArgs
mixin GetTickerProviderStateMixin on BaseController implements TickerProvider {
  Ticker? _ticker;

  @override
  Ticker createTicker(TickerCallback onTick) {
    loggerMsg('createTicker----');

    _ticker ??= Ticker(onTick,
        debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null);

    return _ticker!;
  }

  @override
  void dispose() {
    assert(() {
      if (_ticker == null || !_ticker!.isActive) return true;
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('$this was disposed with an active Ticker.'),
        ErrorDescription(
          '$runtimeType created a Ticker via its SingleTickerProviderStateMixin, but at the time '
          'dispose() was called on the mixin, that Ticker was still active. The Ticker must '
          'be disposed before calling super.dispose().',
        ),
        ErrorHint(
          'Tickers used by AnimationControllers '
          'should be disposed by calling dispose() on the AnimationController itself. '
          'Otherwise, the ticker will leak.',
        ),
        _ticker!.describeForError('The offending ticker was'),
      ]);
    }());
    super.dispose();
  }

  @override
  void update([List<Object>? ids, bool condition = true]) {
    if (_ticker != null) _ticker!.muted = !TickerMode.of(Get.context!);
    super.update(ids, condition);
  }
}
